package com.na.flipcard;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.BmobObject;

import com.na.flipcard.util.GameConfigEx;
import com.na.flipcard.util.GameUtil;
import com.na.game.GameManager;
import com.na.game.flipcard.R;
import com.na.game.platform.sns.SnsListener;
import com.na.game.platform.sns.SnsManager;
import com.na.game.util.Cache;
import com.na.game.util.GameException;
import com.na.game.util.Util;

public class TopsActivity extends Activity implements OnScrollListener {

	private ListView panel;
	private TextView tip;
	private View myRankPanel;
	private TextView myRankNull, myName, myHighest, myAdditive;
	
	private SimpleAdapter adapter;
	private List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
	private static final String COL_RANK = "col_tops_rank";
	private static final String COL_HIGHEST_NUM = "col_highest_num";
	private static final String COL_ADDITIVE_NUM = "col_additive_num";
	
	private static final int BLOCK_LIMIT = 20;
	private int dataMax = -1;
	private int state = STATE_NONE;
	
	private static final int STATE_NONE = 0;
	private static final int STATE_PRE_LOADING = 1;
	private static final int STATE_LOADING = 2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.na_tops_activity);
		
		myRankPanel = findViewById(R.id.na_tops_me);
		myRankNull = (TextView) findViewById(R.id.na_tops_me_null);
		myName = (TextView) findViewById(R.id.na_tops_my_name);
		myHighest = (TextView) findViewById(R.id.na_tops_my_highest);
		myAdditive = (TextView) findViewById(R.id.na_tops_my_additive);
		
		ListView lv = (ListView) findViewById(R.id.na_tops_content);
		tip = (TextView) getLayoutInflater().inflate(R.layout.na_loading, null);
		lv.addFooterView(tip);
		lv.setFooterDividersEnabled(false);
		
		String[] from = new String[]{COL_RANK,
									GameConfigEx.BMOB_TABLE_SCORES_COL_NICKNAME,
									GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST,
									GameConfigEx.BMOB_TABLE_SCORES_COL_ADDITIVE};
		int[] to = new int[]{R.id.na_tops_rank,
							R.id.na_tops_item_nickname,
							R.id.na_tops_item_highest,
							R.id.na_tops_item_additive};
		adapter = new SimpleAdapter(this, data, R.layout.na_tops_list_item, from, to);
		lv.setAdapter(adapter);
		lv.setOnScrollListener(this);
		
		panel = lv;
		
		requestData(BLOCK_LIMIT, null);
		requestMyData();
	}
	
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && state == STATE_PRE_LOADING) {
			state = STATE_LOADING;
			Integer factor = null;
			if (data != null && data.size() > 0) {
				factor = (Integer) data.get(data.size() - 1).get(COL_HIGHEST_NUM);
			}
			requestData(BLOCK_LIMIT, factor);
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		ListView listView = (ListView) view;
		for (int i = view.getChildCount() - listView.getFooterViewsCount() - 1; i >= 0; i--) {
			View child = listView.getChildAt(i);
			if (!(child instanceof LinearLayout)) {
				continue;
			}
			LinearLayout ll = (LinearLayout) child;
			TextView rank = (TextView) ll.getChildAt(0);
			String text = rank.getText().toString();
			if (Util.strEqualsInexact(text, "1.", "2.", "3.")) { // the top 3
				rank.setBackgroundColor(0xfffa804f);
				rank.setTextColor(Color.WHITE);
			} else { // restore
				rank.setBackgroundDrawable(null);
				rank.setTextColor(Color.BLACK);
			}
		}
		
		if (totalItemCount > listView.getFooterViewsCount() && firstVisibleItem + visibleItemCount == totalItemCount && dataMax == -1 && state == STATE_NONE) {
			state = STATE_PRE_LOADING;
			tip.setText("正在努力加载更多,请稍候...");
			panel.addFooterView(tip);
		}
	}

	private void requestData(final int limit, final Integer factor) {
		new Thread() {
			@Override
			public void run() {
				GameManager.get(SnsManager.class).query(GameConfigEx.BMOB_TABLE_SCORES, limit,
														GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST, false,
														factor, new QueryDataListener());
			}
		}.start();
	}
	
	private class QueryDataListener extends SnsListener {
		@Override
		public void queryResult(List<BmobObject> result, GameException ex) {
			state = STATE_NONE;
			if (ex != null) {
				if (dataMax == -1)
					dataMax = 0;
				tip.setText("网络连接错误,请检测您的网络连接是否正常,然后再试试...");
				return;
			}
			int size = result != null ? result.size() : 0;
			if (size == 0 && data.size() == 0) {
				dataMax = 0;
				tip.setText("暂时没有玩家提交分数,赶紧去成为第一人吧");
				return;
			}
			panel.removeFooterView(tip);
			for (int i = 0; i < size; i++) {//fa804f
				BmobObject obj = result.get(i);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put(COL_RANK, (data.size() + 1) + ".");
				map.put(GameConfigEx.BMOB_TABLE_SCORES_COL_NICKNAME, obj.getString(GameConfigEx.BMOB_TABLE_SCORES_COL_NICKNAME));
				map.put(GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST, translate(obj.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST)));
				map.put(GameConfigEx.BMOB_TABLE_SCORES_COL_ADDITIVE, translate(obj.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_ADDITIVE)));
				// extra
				map.put(COL_HIGHEST_NUM, obj.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST));
				map.put(COL_ADDITIVE_NUM, obj.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_ADDITIVE));
				
				data.add(map);
			}
			adapter.notifyDataSetChanged();
			if (size < BLOCK_LIMIT) { // must be get all the data
				dataMax = data.size();
				Toast.makeText(TopsActivity.this, "排行榜已加载完毕", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	private void requestMyData() {
		new Thread() {
			@Override
			public void run() {
				SnsManager sns = GameManager.get(SnsManager.class);
				BmobObject bmob = (BmobObject) Cache.getCache().get(GameConfigEx.CACHE_BMOB_SCORE);
				if (bmob == null) {
					GameUtil.cacheBmob(new QueryMyRankListener(null, QueryMyRankListener.TYPE_GET_OBJ));
					return;
				}
				if (bmob.getString(GameConfigEx.BMOB_TABLE_SCORES_COL_USERID) == null) { // not yet submit
					return;
				}
				requestMyData(sns, bmob);
			}
		}.start();
	}
	
	private void requestMyData(SnsManager sns, BmobObject bmob) {
		sns.queryGreatherThan(GameConfigEx.BMOB_TABLE_SCORES,
				GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST,
				bmob.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST),
				new QueryMyRankListener(bmob, QueryMyRankListener.TYPE_GET_HIGHEST));
		sns.queryGreatherThan(GameConfigEx.BMOB_TABLE_SCORES,
				GameConfigEx.BMOB_TABLE_SCORES_COL_ADDITIVE,
				bmob.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_ADDITIVE),
				new QueryMyRankListener(bmob, QueryMyRankListener.TYPE_GET_ADDITIVE));
	}

	private class QueryMyRankListener extends SnsListener {
		private BmobObject bmob;
		private byte type;
		
		static final byte TYPE_GET_HIGHEST = 0;
		static final byte TYPE_GET_ADDITIVE = 1;
		static final byte TYPE_GET_OBJ = 2;
		
		private QueryMyRankListener(BmobObject bmob, byte type) {
			this.bmob = bmob;
			this.type = type;
		}
		
		@Override
		public void queryResult(List<BmobObject> result, GameException ex) {
			if (ex != null) {
				return;
			}
			switch (type) {
				case TYPE_GET_HIGHEST:
				case TYPE_GET_ADDITIVE:
					myRankNull.setVisibility(View.INVISIBLE);
					myRankPanel.setVisibility(View.VISIBLE);
					myName.setText(bmob.getString(GameConfigEx.BMOB_TABLE_SCORES_COL_NICKNAME));
					myName.setVisibility(View.VISIBLE);
					int rank = result == null ? 1 : result.size() + 1;
					if (type == TYPE_GET_HIGHEST) {
						myHighest.setText(translate(bmob.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST)) + "(第" + rank + "名)");
					} else {
						myAdditive.setText(translate(bmob.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_ADDITIVE)) + "(第" + rank + "名)");
					}
					break;
				case TYPE_GET_OBJ:
					requestMyData(); // retry one time
					break;
			}
		}
	}
	
	private String translate(int num) {
		if (num < 100000) { // 十万
			return String.valueOf(num);
		}
		if (num < 100000000) { // 亿
			int wan = num / 10000;
			int qian = num % 10000 / 1000;
			if (qian == 0) {
				return wan + "万";
			}
			return wan + "." + qian + "万";
		}
		int yi = num / 100000000;
		int qw = num % 100000000 / 10000000;
		if (qw == 0) {
			return yi + "亿";
		}
		return yi + "." + qw + "亿";
	}
}
